package com.ruyuan.eshop.data.migrate.tool.task;

import com.ruyuan.eshop.data.migrate.tool.service.HistoryDataSyncService;
import com.ruyuan.eshop.data.migrate.tool.util.DateFormatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * 历史数据同步处理器
 * @author zhonghuashishan
 * @version 1.0
 */
public class HistoryDataSyncTask implements Runnable {

    private static Logger log = LoggerFactory.getLogger(HistoryDataSyncTask.class);

    private CountDownLatch countDownLatch;

    /**
     * 表名
     */
    private String tableName;

    /**
     * 最小的主键ID
     */
    private Long minId;

    /**
     * 同步截止的最后更新时间
     */
    private Date lastGmtModified;

    /**
     * 一批处理的数据量大小
     */
    private int batchSize;

    private HistoryDataSyncService historyDataSyncService;

    private volatile boolean running;

    public HistoryDataSyncTask(CountDownLatch countDownLatch, String tableName, Long minId, Date lastGmtModified, int batchSize, HistoryDataSyncService historyDataSyncService) {
        this.countDownLatch = countDownLatch;
        this.tableName = tableName;
        this.minId = minId;
        this.lastGmtModified = lastGmtModified;
        this.batchSize = batchSize;
        this.historyDataSyncService = historyDataSyncService;
        running = true;
    }

    @Override
    public void run() {
            log.warn("开始迁移[{}]表的历史数据了，当前时间={}", tableName, DateFormatUtil.formatDateTime(new Date()));

            while (running) {
                try {
                    minId = historyDataSyncService.batchSync(tableName, minId, lastGmtModified, batchSize);
                    if(minId == null) {
                        // 当minId为null时，表示历史数据已经迁移完了
                        log.warn("[{}]表的历史数据已经迁移完了，当前时间={}", tableName, DateFormatUtil.formatDateTime(new Date()));
                        break;
                    }
                } catch (Exception e) {
                    // 把执行出错的记录持久化记录下来 TODO
                    log.error("HistoryDataSyncTask error, tableName:{}, minOrderId:{}, batchSize:{}", tableName, minId, batchSize, e);
                }
            }

            countDownLatch.countDown();

    }


    public void setRunning(boolean running) {
        this.running = running;
    }
}